import { View, Text, Button, Image } from "@tarojs/components";

import './index.less'
import { useEffect, useState } from "react";
import { useRouter } from "@tarojs/taro";
import { fetchBookDetailById } from "@/api/book";


const getStarSum = (rating: number) => {
  const length = Math.floor(rating / 10 / 2);
  return Array.from({ length: length }, () => 1)?.map((item, index) => <Image key={index} className="bookStar" src={require('../../assets/rating.png')}></Image>) ?? []
}


const BookDetail = () => {
 
  const instanse = useRouter()
  const id = instanse.params?.id
  const [love, setLove] = useState(false)
  const [borrow, setBorrow] = useState(false)

  const [detail,setDetail] = useState<any>({})

  const handleClickBorrow = () => {
    setBorrow(!borrow)
  }

  const handleClicklove = () => {
    setLove(!love)
  }

  const getDetail = async () => {
    const res = await fetchBookDetailById(id)
    res?.data && setDetail(res.data)
  }

  useEffect(() => {
    if(id){
      getDetail()
    }
  },[id])
  return (
    <View className="wrapper">
      <View className="detailHeader">
        <Image className="detailBookImage" src={detail.imageUrl}></Image>

        <View className="detailBookContent">
          <View className="detailTitle">{detail.name}</View>
          <View className="detailSubtitle">{detail.author}</View>
          <View className="detailStarBar">{getStarSum(detail.rating)} <Text className="detailStarBarText">{detail.rating}</Text></View>
        </View>
      </View>

      <View className="iconList">
        <View className="iconListItem">
          <Image className="iconListImage" src={require('../../assets/menu.png')}></Image>
          <Text className="iconListText">目录</Text>
        </View>
        <View className="iconListItem" onClick={handleClicklove}>
          <Image className="iconListImage" src={love ? require('../../assets/love_active.png') : require('../../assets/love.png')}></Image>
          <Text className={`iconListText ${love ? 'activeColor' : ''}`}>喜欢</Text>
        </View>
        <View className="iconListItem" onClick={handleClickBorrow}>
          <Image className="iconListImage" src={borrow ? require('../../assets/book_active.png') : require('../../assets/book1.png')}></Image>
          <Text className={`iconListText ${borrow ? 'activeColorBrrow' : ''}`}>加入待读</Text>
        </View>
      </View>

      <View className="bookContent">
        <View className="bookContentTitle">故事简介</View>
        <View className="bookContentText">{detail.dscript}</View>
      </View>

      <View className="bookButtonFixed">

        <View className="bookButton">借阅申请</View>
      </View>

    </View>
  );
};

export default BookDetail;
